package handler

import (
	"github.com/gin-gonic/gin"
	"moon-exam-sys/model"
	"strconv"
)

func UserRopeAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	if uid == 0 || rid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}

	user := model.UserRope{
		Uid: uid,
		Rid: rid,
	}
	model.DB.Create(&user)

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "添加成功",
	})
	return

}

func RopeNodeAdd(c *gin.Context) {
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	if nid == 0 || rid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}

	user := model.RopeNode{
		Rid: rid,
		Nid: nid,
	}
	model.DB.Create(&user)

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "添加成功",
	})
	return
}

func UserAndRope(c *gin.Context) {
	uid := c.Query("uid")
	/*
	   SELECT
	   *
	   FROM
	   ropes
	   LEFT JOIN user_ropes ON user_ropes.rid=ropes.id
	   WHERE
	   user_ropes.uid=1
	*/
	var rope model.Rope
	model.DB.Table("ropes").
		Joins("LEFT JOIN user_ropes ON user_ropes.rid=ropes.id").
		Where("user_ropes.uid=?", uid).
		Debug().
		Find(&rope)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": rope,
	})
}

func RopeAndNode(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		*
		FROM
		nodes
		LEFT JOIN rope_nodes ON rope_nodes.nid=nodes.id
		WHERE
		rope_nodes.rid=1
	*/
	var node model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN rope_nodes ON rope_nodes.nid=nodes.id").
		Where("rope_nodes.rid=?", rid).
		Debug().
		Find(&node)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
}
